<template>
  <view class="container">
    <uni-row>
      <uni-col :span="2">
        <uni-icons type="arrow-left" size="30px" @click="goBack"></uni-icons>
      </uni-col>
      <uni-col style="text-align: center" :span="20">
        <text style="font-size: 26px">指标检测</text>
      </uni-col>
    </uni-row>
    <uni-row>
      <uni-col>
        <!-- 蓝牙连接部分 -->
        <uni-section title="蓝牙状态" type="line" padding>
          <view class="bluetooth-section">
            <text>蓝牙状态: {{ bluetoothStatus }}</text>
            <u-button @click="toggleBluetooth" shape="square" type="primary" size="mini">
              {{ searching ? '停止搜索' : '搜索设备' }}
            </u-button>
            <u-button v-if="isConnected" @click="disconnectDevice" shape="square" type="error" size="mini">
              断开连接
            </u-button>
          </view>

          <!-- 设备列表 -->
          <view v-if="devicesList.length > 0" class="device-list">
            <text class="list-title">可连接设备:</text>
            <view v-for="(item, index) in devicesList" :key="index" class="device-item" @click="ConnectByID(item)">
              <text>{{ item.name || '未知设备' }}</text>
              <text>{{ item.deviceId }}</text>
            </view>
          </view>
        </uni-section>

        <uni-section decoration-color="#1df92f" title="个人信息" type="line" padding style="margin-top: 1vh">
          <view>
            <image src="/static/images/tabbar/mine.png" style="width: 30rpx;height: 30rpx;margin-right: 20rpx"/>
            <text class="uni-btn-text">安捷星 1555555555</text>
          </view>
        </uni-section>

        <uni-section decoration-color="#d81e06" title="检测项" type="line" padding>
          <!-- 检测步骤指示器 -->
          <uni-steps :options="list1" :active="active"/>
        </uni-section>

        <!-- 检测项目部分 -->
        <uni-section class="section" decoration-color="#f7d50d" v-if="active===0" title="心率" type="image"
                     image-url="/static/images/心率.png" padding>
          <uni-row>
            <uni-col :span="20">
              <text class="formData">{{ form.heartRate || '--' }}</text>
            </uni-col>
            <!--            <uni-col style="float: right" :span="4">
                          <u-button @click="readBLECharacteristicValue" class="button" shape="square" :type="form.heartRate ? 'warning' : 'primary'" size="mini">
                            {{ form.heartRate ? '重测' : '开始检测' }}
                          </u-button>
                        </uni-col> -->
          </uni-row>
        </uni-section>

        <uni-section class="section" decoration-color="#f7d50d" v-if="active===0" title="血氧" type="image"
                     image-url="/static/images/血氧.png" padding>
          <uni-row>
            <uni-col :span="20">
              <text class="formData">{{ form.SpO2 || '--' }}</text>
            </uni-col>
            <uni-col style="float: right" :span="4">
              <u-button @click="readBLECharacteristicValue" class="button" shape="square"
                        :type="form.SpO2 ? 'warning' : 'primary'" size="mini">
                {{ form.SpO2 ? '重测' : '开始检测' }}
              </u-button>
            </uni-col>
          </uni-row>
        </uni-section>

        <uni-section class="section" decoration-color="#f7d50d" v-if="active===0" title="血压" type="image"
                     image-url="/static/images/血压.png" padding>
          <uni-row>
            <uni-col :span="20">
              <view v-if="form.diastolic!=''" class="form">血压(低压) {{ form.diastolic }} mmHg</view>
              <view v-else class="form">血压(低压) --</view>
            </uni-col>
          </uni-row>
          <uni-row>
            <uni-col :span="20">
              <view v-if="form.systolic!=''" class="form">血压(高压) {{ form.systolic }} mmHg</view>
              <view v-else class="form">血压(高压) --</view>
            </uni-col>
            <uni-col style="float: right" :span="4">
              <u-button @click="startMeasurement('bloodPressure')" class="button" shape="square"
                        :type="form.diastolic ? 'warning' : 'primary'" size="mini">
                {{ form.diastolic ? '重测' : '开始检测' }}
              </u-button>
            </uni-col>
          </uni-row>
        </uni-section>

        <uni-section class="section" decoration-color="#f7d50d" v-if="active===0" title="呼气酒精" type="image"
                     image-url="/static/images/酒精.png" padding>
          <uni-row>
            <uni-col :span="20">
              <view class="formData">{{ form.alcohol || '--' }}</view>
            </uni-col>
            <uni-col style="float: right" :span="4">
              <u-button @click="startMeasurement('alcohol')" class="button" shape="square"
                        :type="form.alcohol ? 'warning' : 'primary'" size="mini">
                {{ form.alcohol ? '重测' : '开始检测' }}
              </u-button>
            </uni-col>
          </uni-row>
        </uni-section>

        <uni-section v-if="active===1" title="酒精">
          <alcohol/>
        </uni-section>

        <uni-row style="margin-top: 2vh">
          <uni-col :offset="3" :span="8">
            <u-button @click="goBack" style="margin-left: auto;margin-right: auto;" shape="square" type="default">取消
            </u-button>
          </uni-col>
          <uni-col :offset="2" :span="8">
            <u-button @click="submitData" style="margin-left: auto;margin-right: auto;" shape="square" type="primary">
              提交
            </u-button>
          </uni-col>
        </uni-row>
      </uni-col>
    </uni-row>
  </view>
</template>

<script>
import UniSteps from "../../uni_modules/uni-steps/components/uni-steps/uni-steps.vue";
import UniSection from "../../components/uni-section/uni-section.vue";
import SpO2 from "./SpO2.vue";
import Alcohol from "./alcohol.vue";
import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import UniRow from "../../uni_modules/uni-row/components/uni-row/uni-row.vue";
import UniCol from "../../uni_modules/uni-row/components/uni-col/uni-col.vue";

export default {
  components: {UniCol, UniRow, UniIcons, Alcohol, SpO2, UniSection, UniSteps},
  data() {
    return {
      bluetoothStatus: '未连接',
      isConnected: false,
      searching: false,
      connectedDeviceId: '',
      deviceId: '',
      serviceId: '',
      nbpCharacteristicId: "beb5483e-36e1-4688-b7f5-ea07361b26a7", // 血压特征值
      characteristicId: 'beb5483e-36e1-4688-b7f5-ea07361b26a8',
      devicesList: [],
      active: 0,
      list1: [{
        title: '心率血氧血压'
      }, {
        title: '酒精'
      }],
      form: {
        heartRate: "",
        SpO2: "",
        systolic: "100",
        diastolic: "60",
        alcohol: ""
      },
      currentMeasurement: null,
      interval: null
    }
  },
  onLoad() {
    this.initBluetooth();
  },
  onUnload() {
    this.closeBLEConnection();
  },
  methods: {
    goBack() {
      this.$tab.reLaunch('/pages/index')
    },
    change() {
      if (this.active < this.list1.length - 1) {
        this.active += 1
      } else {
        this.active = 0
      }
    },

    // 初始化蓝牙
    initBluetooth() {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log('蓝牙适配器初始化成功', res);
          this.bluetoothStatus = '已就绪';
          this.checkBluetoothState();
        },
        fail: (err) => {
          console.error('蓝牙适配器初始化失败', err);
          this.bluetoothStatus = '初始化失败';
          this.showBluetoothError(err);
        }
      });
    },

    // 检查蓝牙状态
    checkBluetoothState() {
      uni.getBluetoothAdapterState({
        success: (res) => {
          if (res.available) {
            this.bluetoothStatus = res.discovering ? '搜索中...' : '已就绪';
          } else {
            this.bluetoothStatus = '不可用';
          }
        },
        fail: (err) => {
          console.error('获取蓝牙状态失败', err);
          this.bluetoothStatus = '状态获取失败';
        }
      });
    },

    // 切换蓝牙搜索状态
    toggleBluetooth() {
      if (this.searching) {
        this.stopSearch();
      } else {
        this.Search();
      }
    },

    // 搜索蓝牙设备
    Search() {
      if (!this.searching) {
        uni.closeBluetoothAdapter({
          complete: (res) => {
            console.log("关闭蓝牙模块:", res);
            uni.openBluetoothAdapter({
              success: (res) => {
                this.bluetoothStatus = '搜索中...';
                uni.startBluetoothDevicesDiscovery({
                  allowDuplicatesKey: false,
                  success: (res) => {
                    this.searching = true;
                    this.devicesList = [];
                    this.onBluetoothDeviceFound();
                    uni.showToast({
                      title: '正在搜索设备...',
                      icon: 'none'
                    });
                  },
                  fail: (err) => {
                    console.error("开始搜索失败:", err);
                    this.showBluetoothError(err);
                  }
                });
              },
              fail: (err) => {
                console.error("打开蓝牙适配器失败:", err);
                this.showBluetoothError(err);
              }
            });
          }
        });
      }
    },

    // 停止搜索
    stopSearch() {
      uni.stopBluetoothDevicesDiscovery({
        success: (res) => {
          console.log("停止搜索设备:", res);
          this.searching = false;
          this.bluetoothStatus = '已停止搜索';
          uni.showToast({
            title: '已停止搜索',
            icon: 'none'
          });
        },
        fail: (err) => {
          console.error("停止搜索失败:", err);
        }
      });
    },

    // 监听寻找到新设备的事件
    onBluetoothDeviceFound() {
      uni.onBluetoothDeviceFound((devices) => {
        if (devices.devices && devices.devices.length > 0) {
          const newDevices = devices.devices.filter(device => {
            // 过滤条件：设备有名称且包含ESP32（根据实际设备名称调整）
            return device.name && (device.name.includes("ESP32") || device.localName.includes("ESP32"));
          });

          if (newDevices.length > 0) {
            // 去重处理
            newDevices.forEach(newDevice => {
              if (!this.devicesList.some(d => d.deviceId === newDevice.deviceId)) {
                this.devicesList.push(newDevice);
                console.log("发现ESP32设备:", newDevice);
              }
            });
          }
        }
      });
    },

    // 连接设备
    ConnectByID(item) {
      if (!item || !item.deviceId) return;

      this.connectedDeviceId = item.deviceId;
      uni.setStorageSync('pageName', item.name);
      uni.setStorageSync('connectedDeviceId', this.connectedDeviceId);

      uni.showLoading({
        title: '正在连接设备...',
        mask: true
      });

      uni.createBLEConnection({
        deviceId: item.deviceId,
        success: (res) => {
          uni.hideLoading();
          uni.showToast({
            title: '连接成功',
            duration: 2000,
            icon: "none"
          });
          this.isConnected = true;
          this.bluetoothStatus = '已连接: ' + (item.name || '未知设备');
          this.getBLEDeviceServices();
        },
        fail: (err) => {
          console.error("连接失败:", err);
          uni.hideLoading();
          uni.showModal({
            title: '提示',
            content: '连接失败: ' + (err.errMsg || '未知错误'),
            showCancel: false
          });
        }
      });
    },

    // 断开设备连接
    disconnectDevice() {
      if (!this.connectedDeviceId) return;

      uni.closeBLEConnection({
        deviceId: this.connectedDeviceId,
        success: (res) => {
          console.log('断开蓝牙连接成功:', res);
          this.isConnected = false;
          this.bluetoothStatus = '已断开';
          this.connectedDeviceId = '';
          uni.showToast({
            title: '已断开连接',
            icon: 'none'
          });
        },
        fail: (err) => {
          console.error('断开蓝牙连接失败:', err);
          uni.showToast({
            title: '断开连接失败',
            icon: 'none'
          });
        }
      });
    },

    // 获取蓝牙设备的服务uuid
    getBLEDeviceServices() {
      if (!this.connectedDeviceId) return;

      setTimeout(() => {
        uni.getBLEDeviceServices({
          deviceId: this.connectedDeviceId,
          success: (res) => {
            console.log("获取蓝牙设备的服务uuid:", res.services);
            if (res.services && res.services.length > 0) {
              this.services = res.services;
              // 假设第三个服务是我们需要的（根据实际情况调整）
              this.serviceId = res.services[2].uuid;
              this.deviceId = this.connectedDeviceId;
              uni.setStorageSync("serviceId", this.serviceId);
              this.getBLEDeviceCharacteristics();
            } else {
              console.error("未找到可用的服务");
            }
          },
          fail: (err) => {
            console.error("获取服务失败:", err);
          }
        });
      }, 1000);
    },

    // 根据服务uuid获取蓝牙特征值
    getBLEDeviceCharacteristics() {
      if (!this.connectedDeviceId || !this.serviceId) return;

      uni.getBLEDeviceCharacteristics({
        deviceId: this.connectedDeviceId,
        serviceId: this.serviceId,
        success: (res) => {
          console.log("获取蓝牙设备的特征:", res.characteristics);
          // if (res.characteristics && res.characteristics.length > 0) {
          //   for (let i = 0; i < res.characteristics.length; i++) {
          //     const char = res.characteristics[i];
          //     if (char.properties.notify) {
          //       this.characteristicId = char.uuid;
          //     }
          //     if (char.properties.write) {
          //       this.writeId = char.uuid;
          //     }
          //   }
          // if (this.characteristicId) {
          //   uni.setStorageSync("characteristicId", this.characteristicId);
          //   uni.setStorageSync("writeId", this.writeId);
          //   this.readBLECharacteristicValue();
          // } else {
          //   console.error("未找到可用的特征值");
          // }
          // }
        },
        fail: (err) => {
          console.error("获取特征值失败:", err);
        }
      });
    },
    readNBPValue() {
      let _this = this;
      plus.bluetooth.readBLECharacteristicValue({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: this.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceId.toLowerCase(),
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.nbpCharacteristicId,
        success: res => {
          uni.onBLECharacteristicValueChange(function (res) {
            _this.handleBluetoothData((Buffer)(res.value), "bloodPressure")
          });
        },
        fail: res => {
          console.log(res)
        },
      });
    },
    readBLECharacteristicValue() {
      let _this = this;
      console.log("读取SPO2数据")
      plus.bluetooth.readBLECharacteristicValue({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: this.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceId.toLowerCase(),
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.characteristicId,
        success: res => {
          uni.onBLECharacteristicValueChange(function (res) {
            _this.handleBluetoothData((Buffer)(res.value), 'spo2')
          });
        },
        fail: res => {
          console.log(res)
        },
      });
    },

    // 启用特征值订阅
    notifyBLECharacteristicValueChange() {
      uni.notifyBLECharacteristicValueChange({
        deviceId: this.deviceId,
        serviceId: this.serviceId,
        characteristicId: this.characteristicId,
        state: true,
        success: () => {
          console.log("心率血氧启用特征值订阅成功");
          this.onBLECharacteristicValueChange('spo2');
        },
        fail: (err) => {
          console.error("启用特征值订阅失败:", err);
        }
      });
      uni.notifyBLECharacteristicValueChange({
        deviceId: this.deviceId,
        serviceId: this.serviceId,
        characteristicId: this.nbpCharacteristicId,
        state: true,
        success: () => {
          console.log("血压启用特征值订阅成功");
          this.onBLECharacteristicValueChange('bloodPressure');
        },
        fail: (err) => {
          console.error("启用特征值订阅失败:", err);
        }
      });
    },

    // 监听特征值变化
    onBLECharacteristicValueChange(type) {
      uni.onBLECharacteristicValueChange((res) => {
        console.log("接收到蓝牙数据:", res);
        if (res.deviceId === this.deviceId &&
            res.serviceId === this.serviceId &&
            res.characteristicId === this.characteristicId) {
          this.handleBluetoothData(res.value, type);
        }
      });
    },

    // ArrayBuffer转16进制字符串
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
          }
      )
      return hexArr.join('')
    },

    // 写入BLE特征值
    writeBLECharacteristicValue(value) {
      if (!this.deviceId || !this.serviceId) {
        console.error("缺少必要的蓝牙参数");
        return;
      }

      // 将字符串转换为ArrayBuffer
      const buffer = new ArrayBuffer(value.length);
      const dataView = new DataView(buffer);
      for (let i = 0; i < value.length; i++) {
        dataView.setUint8(i, value.charCodeAt(i));
      }
      uni.writeBLECharacteristicValue({
        deviceId: this.deviceId,
        serviceId: this.serviceId,
        characteristicId: "beb5483e-36e1-4688-b7f5-ea07361b26a8",
        value: buffer,
        success: (res) => {
          console.log("写入成功:", value);
        },
        fail: (err) => {
          console.error("写入失败:", err);
        }
      });
    },

    // 关闭蓝牙连接
    closeBLEConnection() {
      if (this.connectedDeviceId) {
        uni.closeBLEConnection({
          deviceId: this.connectedDeviceId,
          success: (res) => {
            console.log('断开蓝牙连接成功');
          },
          fail: (err) => {
            console.error('断开蓝牙连接失败:', err);
          }
        });
      }

      if (this.searching) {
        this.stopSearch();
      }

      uni.closeBluetoothAdapter({
        success: (res) => {
          console.log('关闭蓝牙适配器成功');
        }
      });
    },

    // 显示蓝牙错误
    showBluetoothError(err) {
      let content = '蓝牙操作失败';
      if (err.errCode === 10001) {
        content = '蓝牙未打开，请打开蓝牙后再试';
      } else if (err.errMsg) {
        content = err.errMsg;
      }

      uni.showModal({
        title: "提示",
        content: content,
        showCancel: false,
        confirmColor: "#008fd6",
      });
    },

    // 提交数据
    submitData() {
      // 验证数据
      if (!this.form.heartRate || !this.form.SpO2 ||
          !this.form.systolic || !this.form.diastolic ||
          !this.form.alcohol) {
        uni.showToast({
          title: '请完成所有检测项目',
          icon: 'none'
        });
        return;
      }

      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      // 这里添加实际的数据提交逻辑
      console.log('提交数据:', this.form);

      // 模拟提交
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });

        // 返回首页
        setTimeout(() => {
          this.$tab.reLaunch('/pages/index');
        }, 1500);
      }, 2000);
    },

    // 以下是数据解析方法，需要根据实际设备协议实现
    parseHeartRate(data) {
      // 示例：假设数据格式为 "HR:75"
      const match = data.match(/HR:(\d+)/);
      return match ? match[1] : '--';
    },

    parseSpO2(data) {
      // 示例：假设数据格式为 "SPO2:98"
      const match = data.match(/SPO2:(\d+)/);
      return match ? match[1] + '%' : '--';
    },

    parseBloodPressure(data) {
      // 示例：假设数据格式为 "BP:120/80"
      const match = data.match(/BP:(\d+)\/(\d+)/);
      return match ? {high: match[1], low: match[2]} : {high: '--', low: '--'};
    },

    parseAlcohol(data) {
      // 示例：假设数据格式为 "ALC:0.05"
      const match = data.match(/ALC:(\d+\.\d+)/);
      return match ? match[1] + '%' : '--';
    },
    // 处理蓝牙数据
    handleBluetoothData(value, property) {
      // 将ArrayBuffer转换为字符串
      const dataString = this.ab2str(value);
      console.log(dataString);
      switch (property) {
        case 'bloodPressure':
          try {
            if (dataString.includes(',')) {
              // 解析格式: 收缩压,舒张压 (例如: "113,74")
              const parts = dataString.split(',');
              if (parts.length >= 2) {
                const systolic = parts[0].trim();
                const diastolic = parts[1].trim();
                // 更新表单数据
                if (Number(systolic) > 20) {
                  this.form.systolic = systolic;
                }
                if (Number(diastolic) > 20) {
                  this.form.diastolic = diastolic;
                }
                uni.hideLoading();
                clearInterval(this.interval)
              }
            } else {
              console.log("实时压力:", dataString)
            }

          } catch (err) {
            console.error("数据处理错误:", err);
          }
          break;
        case 'alcohol':
          break;
        case 'spo2':
          try {
            // 解析格式: 心率,血氧 (例如: "88,96")
            const parts = dataString.split(',');
            if (parts.length >= 2) {
              const heartRate = parts[0].trim();
              const SpO2 = parts[1].trim();

              // 更新表单数据
              if (this.isValidHeartRate(heartRate)) {
                this.form.heartRate = heartRate;
              }
              if (this.isValidSpO2(SpO2)) {
                this.form.SpO2 = SpO2 + '%';
              }

              // 根据当前测量类型隐藏加载状态
              if (this.currentMeasurement === 'heartRate' || this.currentMeasurement === 'SpO2') {
                uni.hideLoading();
              }
            }
          } catch (err) {
            console.error("数据处理错误:", err);
          }
        default:
          break;
      }
    },

// ArrayBuffer转字符串
    ab2str(buffer) {
      const uint8Array = new Uint8Array(buffer);
      let str = '';
      for (let i = 0; i < uint8Array.length; i++) {
        str += String.fromCharCode(uint8Array[i]);
      }
      return str;
    },

// 验证心率值是否有效
    isValidHeartRate(value) {
      const hr = parseInt(value);
      return !isNaN(hr) && hr > 30 && hr < 220;
    },

// 验证血氧值是否有效
    isValidSpO2(value) {
      const spo2 = parseInt(value);
      return !isNaN(spo2) && spo2 >= 70 && spo2 <= 100;
    },

// 开始测量方法也需要相应调整
    startMeasurement(type) {
      if (!this.isConnected) {
        uni.showToast({
          title: '请先连接设备',
          icon: 'none'
        });
        return;
      }

      this.currentMeasurement = type;

      // 根据不同的测量类型发送不同的指令
      let command = '';
      switch (type) {
        case 'heartRate':
          command = 'GET_HR'; // 获取心率指令
          break;
        case 'SpO2':
          command = 'GET_SPO2'; // 获取血氧指令
          break;
        case 'bloodPressure':
          // 血压测量可能需要不同的处理方式
          command = 'START_BP';
          break;
        case 'alcohol':
          // 酒精测量可能需要不同的处理方式
          command = 'STOP_BP';
          break;
      }

      // 发送指令到设备
      this.writeBLECharacteristicValue(command);

      uni.showLoading({
        title: '测量中...',
        mask: true
      });
      //每秒读取设备数据
      this.interval = setInterval(() => {
        console.log('读取设备数据')
        this.readNBPValue();
      }, 1000);
      //设置超时，防止长时间无响应
      this.measurementTimeout = setTimeout(() => {
        uni.hideLoading();
        if (this.form.systolic == '') {
          uni.showToast({
            title: '测量超时',
            icon: 'none'
          });
        }
        clearInterval(this.interval);
      }, 90000); // 90秒超时
    },
  }
}
</script>

<style lang="scss">
page {
  margin-top: 5vh;
  background-color: #ffffff;
}

.container {
  padding: 20rpx;
}

.bluetooth-section {
  display: flex;
  flex-direction: column;
  gap: 10rpx;

  > view {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.device-list {
  margin-top: 20rpx;
  border-top: 1px solid #eee;
  padding-top: 10rpx;

  .list-title {
    font-weight: bold;
    margin-bottom: 10rpx;
    display: block;
  }

  .device-item {
    padding: 15rpx;
    border-bottom: 1px solid #f5f5f5;

    > text {
      display: block;

      &:first-child {
        font-size: 28rpx;
        margin-bottom: 5rpx;
      }

      &:last-child {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.formData {
  font-size: 50rpx;
}

.section {
  margin-bottom: 2rpx;
}

.form {
  margin-top: 20rpx;
  font-size: 30rpx;
}

.button {
  margin-bottom: 20rpx;
  margin-right: 20rpx;
  float: right;
}
</style>